<style lang="scss">
// 去除圆角
main.main-wrapper > section.tablelist .tablelist-content {
    .tablelist-searchs {
        border-radius: 0;
    }
}
main.main-wrapper > section.tablelist .tablelist-table {
    // 去除圆角
    border-radius: 0;
    table {
        min-width: 1430px;
        // font-size: 10px;
    }
    // 解决Safari下横向滚动条无法拖动问题
    .vview-custome-resize-triggers,
    .vview-custome-resize-triggers > div,
    .vview-contract-resize-trigger:before {
        height: 1px;
    }
}
// 小屏幕优化
@media screen and (max-width: 1440px) {
    main.main-wrapper > section.tablelist .tablelist-table {
        table {
            min-width: 1190px;
        }
    }
}
@media screen and (max-width: 1366px) {
    main.main-wrapper > section.tablelist .tablelist-table {
        table {
            min-width: 1100px;
        }
    }
}
// 阴影太重，减轻
.vview-table-left-fixed {
    // box-shadow: 2px 2px 10px #d3d3d3;
    box-shadow: 1px 1px 2px #d3d3d3;
    // box-shadow: none;
}
.tablelist-search {
    position: relative;
    & > .tablelist-content {
        padding-left: 155px;
    }
}
.tablelist-table {
    border-radius: 8px;
    .ivu-table td, .ivu-table th, .ivu-table-cell {
        text-overflow: clip;
    }
    .ivu-table-cell {
        padding: 8px;
    }
}
// .tablelist-tabs {
// 	border-bottom: 1px solid #2d8cf0;
// 	margin-bottom: 10px;
// 	.vview-button {
// 		min-width: 100px;
// 		height: 36px;
// 		border-radius: 0 !important;
// 	}
// }

// .tablelist-searchs {
// 	padding: 10px 10px 0;
// 	background-color: #fff;
// 	border: 1px solid #ddd;
// 	margin-bottom: 10px;
// 	border-radius: 8px;
// 	.vview-formitem {
// 		margin-bottom: 10px;
// 	}
// }
.tablelist-tree-wrapper {
    position: absolute;
    top: 0;
    left: -5px;
    z-index: 1;
    min-height: calc(100% - 48px);
}
.tablelist-page-container {
    // margin-top: 15px;
    margin-left: 5px;
    display: inline-flex;
    justify-content: right;
    align-items: center;

    .table-setting {
        // margin-right: 15px;
        padding: 6px;
        border: 1px solid #dcdee2;
        border-radius: 5px;
        background-color: #fff;
        cursor: pointer;
        &:hover {
            color: #5cadff;
            border-color: #5cadff;
        }

        .icon-setting {
            margin: 0;
            color: #515a6e;
            &:hover {
                color: #5cadff;
            }
        }
    }

    .setting-active {
        border-color: #2d8cf0;
        .icon-setting {
            color: #2d8cf0;
        }
    }

    .setting-content {
        font-size: 12px;
        // width: 400px;
        .setting-item {
            display: flex;
            justify-content: space-between;
            padding: 10px 0;
            .item-name {
                flex: 1;
                text-align: left;

                .item-move-icon {
                    padding: 2px;
                    border: 1px solid #2d8cf0;
                    border-radius: 4px;
                    cursor: move;
                    color: #2d8cf0;
                    margin-right: 15px;
                }
            }
            .item-switch {
                width: 60px;
                text-align: right;
            }
        }
        .settint-other-content {
            padding-top: 15px;
            .setting-other-item {
                padding-bottom: 10px;
                display: flex;
                justify-content: space-between;
                align-items: center;
            }
            .setting-reset-icon {
                border: 1px solid #dcdee2;
                padding: 5px;
                border-radius: 8px;
                cursor: pointer;
                &:hover {
                    color: #2d8cf0;
                    border-color: #2d8cf0;
                }
            }
        }
    }

    .tablelist-page {
        margin-top: 0;
        display: flex;
        justify-content: flex-end;
    }
}


.tablelist-tools {
    margin-bottom: 5px;
    & > * {
        margin-right: 5px;
    }
    .vview-dropdown {
        position: relative;
    }
    .vview-dropdown-list {
        min-width: 100%;
        & > * {
            line-height: 16px;
            display: block;
        }
        & > *:not(:last-child) {
            border-bottom: 1px solid #ddd;
        }
    }
}

.tablelist-dropdown {

    .ivu-select-dropdown {
        // width: 56px;
        min-width: 56px;
    }
    .tablelist-dropdown-menu {
        & > * {
            line-height: 16px;
            display: block;
            color: #515a6e;
            cursor: pointer;
            padding: 5px 10px;
            // background-color: #;
            &:hover {
                background-color: #f8f8f9;
            }
        }
        & > *:not(:last-child) {
            border-bottom: 1px solid #ddd;
        }
    }
}
.customtablelist-poptip {
    width: 100%;
    .ivu-poptip-rel {
        width: 100%;
    }
    &-render-container {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;

        & > div, span {
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
    }
}
</style>

<template>
    <section :class="{ tablelist: true, 'tablelist-search': showTreeSearchs }">
        <compTreeSearch
            class="tablelist-tree-wrapper"
            v-if="showTreeSearchs"
            v-bind="getTreeSearchsAttrs"
            @on-search="cleanUpdateSearch"
            ref="treeSearch"
        ></compTreeSearch>
        <div class="tablelist-content">
            <compTabSearch
                v-if="showTabs"
                v-bind="getTabsAttrs"
                :formData="formData"
                @on-search="cleanUpdateSearch"
                @on-tabs-change="handleTabsChange"
                :showSpan="getContextAttrs.spanTabs"
                :spanNumData="spansData"
                ref="tabSearch"
            ></compTabSearch>
            <!-- <vButtonGroup v-if="showTabs" class="tablelist-tabs clearfix" compact>
				<Button
					v-for="(item,index) in getCompsData('Tabs')"
					:key="index"
					:theme="handleActiveTab(item)"
					@click.native="handleTabsSearch(item)"
				>{{handleCompatibleLabel(item)}}</Button>
			</vButtonGroup>-->
            <compSearchs
                v-if="showSearchs"
                ref="compSearchs"
                v-bind="getSearchsAttrs"
                @on-search="updateSearch"
                @on-change-search="changeSearch"
            >
                <template #header>
                    <div v-if="showTools" :class="getToolsPosClass">
                        <compOperateLink
                            v-for="(item, index) in getVisibleTools"
                            :key="index"
                            :isButton="true"
                            :data="item"
                            @on-click="handleOperates"
                        ></compOperateLink>
                        <Dropdown v-if="getMoreTools.length" trigger="click">
                            <Button>
                                {{ $ct("global.common.operation") }}
                                <!-- <vIcon type="arrow-dropdown" /> -->
                                <Icon type="md-arrow-dropdown" />
                            </Button>
                            <template #list>
                                <compOperateLink
                                    v-for="(item, index) in getMoreTools"
                                    :key="index"
                                    :data="item"
                                    @on-click="handleOperates"
                                ></compOperateLink>
                            </template>
                        </Dropdown>
                    </div>
                </template>
                <template #searchButton>
                    <div class="tablelist-page-container">
                        <Poptip v-model="settingActive" title="列设置" trigger="click" placement="bottom-end" @on-popper-hide="handleSettingDifference">
                            <Button :class="`table-setting ${settingActive ? 'setting-active' : ''}`">
                                <Icon class="icon-setting" type="ios-settings-outline" />
                                <!-- &nbsp; -->
                                <!-- 表格设置 -->
                            </Button>
                            <template #content>
                                <div class="setting-content">
                                    <div class="setting-list">
                                        <div class="setting-item item-header">
                                            <div class="item-name font-bold">
                                                列名（可拖拽排序）
                                            </div>
                                            <div class="item-switch font-bold">
                                                显示
                                            </div>
                                            <div class="item-switch font-bold">
                                                排序
                                            </div>
                                            <div class="item-switch font-bold">
                                                拖动列宽
                                            </div>
                                            <div class="item-switch font-bold">
                                                是否固定
                                            </div>
                                        </div>
                                        <draggable
                                            v-model="tableColumns"
                                            group="people"
                                            @start="drag=true"
                                            @end="drag=false"
                                            item-key="id">
                                            <template #item="{element}">
                                                <div class="setting-item">
                                            <!-- <div class="setting-item" v-for="item in tableColumns"> -->
                                                    <div class="item-name">
                                                        <span>
                                                            <Icon class="item-move-icon" type="md-move" />
                                                        </span>
                                                        <span>{{element.title ? element.title : '选择列'}}</span>
                                                    </div>
                                                    <div class="item-show item-switch">
                                                        <Switch size="small" v-model="element.show"></Switch>
                                                    </div>
                                                    <div class="item-sort item-switch">
                                                        <Switch v-if="!element.type" size="small" v-model="element.sortable"></Switch>
                                                    </div>
                                                    <div class="item-resize item-switch">
                                                        <Switch size="small" v-model="element.resizable"></Switch>
                                                    </div>
                                                    <div class="item-fixed item-switch">
                                                        <Switch size="small" v-model="element.fixed" trueValue="left" :falseValue="false"></Switch>
                                                    </div>
                                            <!-- </div> -->
                                                </div>
                                            </template>
                                        </draggable>
                                        <div class="settint-other-content">
                                            <div class="setting-fix-height setting-other-item">
                                                <span class="font-bold">固定表格高度（行内滚动）</span>
                                                <Switch size="small" v-model="fixTableHeight"></Switch>
                                            </div>
                                            <div class="setting-reset setting-other-item">
                                                <span class="font-bold">一键还原所有设置</span>
                                                <Icon class="setting-reset-icon" size="20" type="md-refresh" @click="resetTableColumns" />
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </Poptip>
                    </div>
                </template>
                <!-- <template slot-scope="{search}">
					<Button
						style="margin-left:5px;"
						theme="primary"
						icon="search"
						@click.native="search('search')"
					>{{$t('global.common.search')}}</Button>
					<Button
						style="margin-left:5px;"
						icon="refresh"
						@click.native="search('reset')"
					>{{$t('global.common.reset')}}</Button>
					<Button
						v-if="handleMoreSearchs"
						style="margin-left:5px;"
						theme="dashed"
						@click.native="search('more')"
					>
						{{$t('global.common.searchs')}}&nbsp;
						<vIcon type="ios-arrow-down"></vIcon>
					</Button>
				</template>-->
            </compSearchs>
            <div ref="compTool">
                <!-- <slot name="tools"></slot> -->
                <componentFuncional :toolsRender="toolsRender"></componentFuncional>
            </div>
            <!-- <Table
                class="tablelist-table"
                v-bind="getTableAttrs"
                v-on="getListeners"
                :height="computedHeight"
                ref="table"
            ></Table> -->
            <Table
                size="small"
                class="tablelist-table"
                v-bind="getTableAttrs"
                v-on="getListeners"
                :columns="getShowTableColumns"
                :height="fixTableHeight ? computedHeight : undefined"
                ref="table"
            ></Table>
            <Page
                ref="compPage"
                v-if="showPage"
                class="tablelist-page"
                @on-change="updatePage"
                @on-page-size-change="updateRows"
                v-bind="getPageAttrs"
            ></Page>
            <slot name="footer"></slot>
        </div>
        <template ref="comTemplate" v-if="showPlugins">
            <compModal
                v-model="operate.show"
                v-bind="operate"
                @on-confirm="updateList()"
                @on-close="handleModalClose"
                :closable="propsclosable"
            >
                <component
                    v-if="operate.component"
                    :is="operate.component"
                    v-bind="operate"
                    v-on="operate.on"
                    @on-closeCloseable="closeCloseable"
                    @on-openCloseable="openCloseable"
                    @on-close="handleModalClose"
                    @on-update="updateSearch"
                    @on-current-page-update="updateSearch({}, formData.page, true)"
                />
            </compModal>
            <slot name="plugins"></slot>
        </template>
    </section>
</template>
<script>
import draggable from "vuedraggable";
import compUpload from "./upload";
import compSearchs from "./searchs";
import compOperateLink from "./operate-link";
import compTreeSearch from "./tree-search";
import compTabSearch from "./tab-search";
import { h, renderSlot, resolveComponent } from 'vue';
// 函数式组件，用于toolsRender渲染
const componentFuncional = (props, context) => {
    if (typeof props.toolsRender == "function") {
        return props.toolsRender();
    }
};
export default {
    inheritAttrs: false,
    props: {
        initFormData: Object,
        startUp: Boolean,
        // toolsRender: Function
    },
    components: {
        draggable,
        compUpload,
        compSearchs,
        compOperateLink,
        compTreeSearch,
        compTabSearch,
        componentFuncional
    },
    data() {
        return {
            loading: false,
            total: 0,
            dataList: [],
            checkedData: [],
            checkedRowData: [],
            formData: {
                search: {},
            },
            operate: {
                show: false,
                loading: false,
            },
            propsclosable: true,
            spansData: {},
            computedHeight: null,
            queryPage: false,
            settingActive: false,
            tableColumns: [],
            fixTableHeight: false,
            drag: false,
            myArray: [
                {
                    name: "test1"
                },
                {
                    name: "test2"
                }
            ],
        };
    },
    beforeCreate() {
        this.$emit("on-context", this);
    },
    created() {
        this.loadTableColumns();
        // this.resetTableColumns();
        // if (typeof this.toolsRender === "function") {
            //自定义工具操作栏
            // this.$slots.tools = this.toolsRender(h);
            // this.$forceUpdate();
        // }
        this.formData = {
            ...(this.showPage
                ? { page: 1, rows: 10, sidx: "id", sord: "desc" }
                : {}),
            ...this.formData,
            ...this.initFormData,
        };
        if (this.startUp && !this.showSearchs) this.updateList();
    },
    mounted() {
        // this.$bus.on("changeaside", value => {
        //     //自定义工具操作栏
        //     this.$nextTick(()=>{
        //         if (typeof this.toolsRender === "function") {
        //             this.$slots.tools = this.toolsRender(h);
        //             this.$forceUpdate()
        //         }
        //     })
        // });
        window.onresize = this.resizeThrottle(() => {
            // console.log("resize执行一次");
            this.computedTableHeight().then((height) => {
                this.computedHeight = height;
            });
        }, 50);
        this.$nextTick(() => {
            // console.log(this.$refs.compPage);
            let pageDom = this.$refs.compPage.$el;
            pageDom.addEventListener('click', (e) => {
                if (e.target.className === 'vview-page-active') {
                    console.log(e.target.innerHTML);
                    if (!this.queryPage) {
                        this.updateList({ page: this.formData.page, rows: this.formData.rows });
                    }
                }
            });
        })
    },
    beforeUnmount() {
        window.onresize = null;
    },
    watch: {
        startUp(val) {
            if (val) this.updateList();
        },
    },
    computed: {
        options() {
            return {
                shortcuts: [
                    {text: '最近7天',
                        value () {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                            return [start, end];
                        }
                    },
                    {text: '最近14天',
                        value () {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 14);
                            return [start, end];
                        }
                    },
                    {text: '最近30天',
                        value () {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                            return [start, end];
                        }
                    },
                    {text: '本月',
                        value () {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.setDate(1));
                            return [start, end];
                        }
                    },
                    {text: '上月',
                        value () {
                            const end = new Date().setDate(0);
                            const start = new Date(new Date().getFullYear(), new Date().getMonth()-1, 1);
                            start.setTime(start);
                            return [start, end];
                        }
                    },
                    {text: '近半年',
                        value () {
                            const end = new Date();
                            const start = new Date();
                            start.setTime(start.getTime() - 3600 * 1000 * 24 * 182);
                            return [start, end];
                        }
                    },
                    // {text: this.$t("global.common.latest_quarter",{defaultValue:'最近一季度'}),
                    //     value () {
                    //         const end = new Date();
                    //         const start = new Date();
                    //         start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                    //         return [start, end];
                    //     }
                    // }
                ]
            }
        },
        getContextAttrs() {
            return this.isMixin ? this : this.$attrs;
        },
        //静态分页
        getPageData() {
            const { isStatic } = this.getContextAttrs.Page || {};
            const data = this.getContextAttrs.data || this.dataList;
            if (isStatic && Array.isArray(data)) {
                const { page = 1, rows = 10 } = this.formData;
                this.total = data.length;
                return data.slice((page - 1) * rows, page * rows);
            }
            return data;
        },
        getVisibleTools() {
            return (this.getCompsData("Tools") || []).filter(function (item) {
                return item.more !== true && item.show !== false;
            });
        },
        getMoreTools() {
            return (this.getCompsData("Tools") || []).filter(function (item) {
                return item.more === true && item.show !== false;
            });
        },
        //定位工具
        getToolsPosClass() {
            const Tools = this.getContextAttrs.Tools || {};
            const posMap = {
                top: "pull-left width-100per",
                topRight: "pull-left width-100per text-right",
                // left: 'pull-left',
                right: "pull-right",
            };
            const pos = posMap[Tools.align] || "pull-left";
            return `tablelist-tools ${pos}`;
        },
        // showSpan(){
        //     return
        // },
        showTabs() {
            const Tabs = this.getContextAttrs.Tabs || {};
            return Tabs.show && this.getCompsData("Tabs") instanceof Array;
        },
        showTools() {
            const Tools = this.getContextAttrs.Tools || {};
            return Tools.show && this.getCompsData("Tools") instanceof Array;
        },
        showSearchs() {
            const Searchs = this.getContextAttrs.Searchs || {};
            return Searchs.show;
        },
        showTreeSearchs() {
            const TreeSearchs = this.getContextAttrs.TreeSearchs || {};
            return TreeSearchs.show;
        },
        showPage() {
            const Page = this.getContextAttrs.Page || { show: true };
            return Page.show;
        },
        showPlugins() {
            const Plugins = this.getContextAttrs.Plugins || {};
            return Plugins.show;
        },
        getPageAttrs() {
            return {
                showSizer: true,
                showElevator: true,
                showTotal: true,
                pageSizeOpts: [10, 20, 50, 100],
                ...(this.getContextAttrs.Page || {}),
                total: this.total,
                pageSize: this.formData.rows,
                current: this.formData.page,
                modelValue: this.formData.page
            };
        },
        getSearchsAttrs() {
            const Searchs = this.getContextAttrs.Searchs || {},
                data = this.getCompsData("Searchs");
            return { ...Searchs, data };
        },
        getTabsAttrs() {
            const Tabs = this.getContextAttrs.Tabs || {},
                data = this.getCompsData("Tabs");
            const Adaptive = this.getContextAttrs.Adaptive || {};
            return { ...Tabs, defaultKey: Tabs.key, data, Adaptive };
        },
        getTreeSearchsAttrs() {
            const TreeSearchs = this.getContextAttrs.TreeSearchs || {},
                data = this.getCompsData("TreeSearchs");
            return { ...TreeSearchs, defaultKey: TreeSearchs.key, data };
        },
        getTableAttrs() {
            const columns = (this.getContextAttrs.columns || []).map((item) => {
                const { langKey, title } = item;
                return {
                    ...item,
                    title: langKey
                        ? this.$ct(langKey, { defaultValue: title })
                        : title,
                };
            });
            if (!this.isMixin) {
                columns.forEach((item) => {
                    Object.keys(item).forEach((key) => {
                        const element = item[key];
                        if (typeof element === "function")
                            item[key] = element.bind(this);
                    });
                });
            }
            return {
                border: true,
                stripe: true,
                hover: true,
                loading: this.loading,
                data: this.getPageData,
                ...this.getContextAttrs.Table,
                columns,
                noDataText: this.$ct("global.common.noDataText"),
            };
        },
        getListeners() {
            return {
                "on-sort-change": this.sortChange,
                "on-filter-change": this.filterChange,
                "on-selection-change": this.checkChange,
                "on-radio-change": this.checkChange,
                ...this.$listeners,
            };
        },
        getShowTableColumns () {
            let showColumns = this.tableColumns.filter(item => {
                return item.show == true;
            })
            // .map(item => {
            //     let { render, ...result } = {
            //         // 默认展示Poptip
            //         poptip: true,
            //         ...item
            //     };
            //     // 是否超出文字隐藏且展示Poptip 设置过key的单元格才展示
            //     if (result.poptip && result.key) {
            //         result.render = (h, { row }) => {
            //             let text;
            //             if (render) {
            //                 // 修改render指针
            //                 text = render.bind(this);
            //             }
            //             else {
            //                 if (!row[result.key]) return null;
            //                 text = row[result.key];
            //             }
            //             // let text = render ? render(h, { row }) : row[result.key];
            //             return (
            //                 h(resolveComponent("Poptip"), {
            //                     class: "customtablelist-poptip",
            //                     trigger: result.poptip.trigger || "hover",
            //                     wordWrap: true,
            //                     width: result.poptip.width,
            //                 }, {
            //                     default: () => {
            //                         return (
            //                             <div class="customtablelist-poptip-render-container">
            //                                 {typeof text == 'function' ? text(h, { row }) : text}
            //                             </div>
            //                         );
            //                     },
            //                     content: () => {
            //                         return <div class="text-center">{typeof text == 'function' ? text(h, { row }) : text}</div>;
            //                     }
            //                 })
            //             );
            //         }
            //     }
            //     result = {
            //         render: render || null,
            //         ...result,
            //     };
            //     return result;
            // });
            return showColumns;

        }
    },
    methods: {
        // // 调整列宽事件
        // handleResizeTable (newWidth, oldWidth, column, event) {
        //     console.log("resize", newWidth, oldWidth, column, event);
        //     let targetColumn = this.tableColumns.find(item => {
        //         return item.title == column.title && item.key == column.key;
        //     });
        //     targetColumn.width = newWidth;
        // },
        loadTableColumns () {
            let routeName = this.$route.name;
            const TABLESETTING = JSON.parse(localStorage.getItem("CUSTOM_TABLE_SETTING") || "{}");
            console.log("TABLESETTING", TABLESETTING);
            // 是否存在用户保存的自定义table设置
            if (!TABLESETTING || !TABLESETTING[routeName]) return this.resetTableColumns();
            const { columns, fixTableHeight } = TABLESETTING[routeName];
            console.log("TABLESETTING[routeName]", TABLESETTING[routeName]);
            this.tableColumns = this.mergeSetting(this.getContextAttrs.columns, columns);
            this.fixTableHeight = fixTableHeight;
        },
        handleSettingDifference () {
            console.log("hideSetting", this.tableColumns);
            console.log("originTableColumns", this.getContextAttrs.columns);
            // 原始值
            const { columns, fixTableHeight } = this.handleColumnsSetting(this.getContextAttrs.columns || []);
            // 对比用户是否有改动
            let isDifferent = false;
            let tableSetting = JSON.parse(localStorage.getItem("CUSTOM_TABLE_SETTING") || "{}");
            if (tableSetting.fixTableHeight != this.fixTableHeight) {
                isDifferent = true;
            }
            else {
                columns.forEach(originItem => {
                    if (isDifferent) return;
                    let nowItem = this.tableColumns.find(item => {
                        return item.title == originItem.title;
                    });
                    let differentKey = Object.keys(nowItem).find(key => {
                        return nowItem[key] != originItem[key];
                    });
                    if (!differentKey) isDifferent = true;
                });
            }
            console.log("是否有不同", isDifferent);
            if (isDifferent) {
                const ROUTENAME = this.$route.name;
                const TABLEDATA = this.handleColumnsSetting(this.tableColumns, this.fixTableHeight);
                tableSetting[ROUTENAME] = {
                    ...TABLEDATA
                };
                console.log("即将写入的数据", JSON.parse(JSON.stringify(tableSetting)));
                localStorage.setItem("CUSTOM_TABLE_SETTING", JSON.stringify(tableSetting));
            }
        },

        resetTableColumns () {
            // this.tableColumns = this.handleColumnsSetting(this.getContextAttrs.columns || []);
            let setting = this.handleColumnsSetting(this.getContextAttrs.columns || []);
            let columnsData = this.mergeSetting(this.getContextAttrs.columns, setting.columns);
            this.tableColumns = columnsData;
            this.fixTableHeight = setting.fixTableHeight;
            let routeName = this.$route.name;
            let settingData = JSON.parse(localStorage.getItem("CUSTOM_TABLE_SETTING") || "{}");
            console.log("resetTableColumns", columnsData);
            if (!settingData || !settingData[routeName]) return;
            settingData[routeName] = undefined;
            localStorage.setItem("CUSTOM_TABLE_SETTING", JSON.stringify(settingData));
        },
        // columns相关配置映射
        handleColumnsSetting (originColumns = [], fixTableHeight = true) {
            let columns = originColumns.map(item => {
                let { sortable = false, resizable = true, show = true, fixed = item.fixed, title, type } = { ...item };
                return {
                    show,
                    title,
                    type,
                    sortable,
                    resizable,
                    fixed
                };
            });
            return {
                columns,
                fixTableHeight
            };
        },
        mergeSetting (originColumns = [], columnsSetting = []) {
            let columns = originColumns.map((item, index) => {
                let settingItem = columnsSetting[index];
                let { sortable = false, resizable = true, show = true, fixed = item.fixed } = { ...settingItem };
                return {
                    ...item,
                    sortable,
                    resizable,
                    show,
                    fixed
                };
            });
            return columns;
        },
        handleModalClose () {
            this.operate.show = false;
            // 解决关闭modal时直接清空operate会闪过一个小modal
            setTimeout(() => {
                this.operate = {};
            }, 200);
            // this.operate = {};
        },
        // 默认容错，mixin模式可重写此函数
        handleTabsChange (searchData) {},
        // 点击更多搜索改变高度时重新计算表格高度
        async changeSearch () {
            await this.$nextTick();
            this.computedTableHeight().then(height => {
                this.computedHeight = height;
            })
        },
        // 函数节流
        resizeThrottle(func, delay) {
            let prev = Date.now();
            return function () {
                let that = this;
                let arg = arguments;
                let now = Date.now();
                if (now - prev >= delay) {
                    func.apply(that, arg);
                    prev = Date.now();
                }
            };
        },
        // 计算表格高度以自适应
        async computedTableHeight() {
            let windowHeight = document.body.offsetHeight;
            let treeSearchHeight = 0,
                tabSearchHeight = 0,
                compSearchsHeight = 0,
                compToolHeight = 0,
                compPageHeight = 0,
                comTemplateHeight = 0;
            await this.$nextTick();
            if (this.$refs.treeSearch) {
                treeSearchHeight = this.$refs.treeSearch.$el.offsetHeight;
                // console.log('treeSearch', this.$refs.treeSearch.$el, treeSearchHeight)
            }
            if (this.$refs.tabSearch) {
                tabSearchHeight = this.$refs.tabSearch.$el.offsetHeight;
                // console.log('tabSearch', this.$refs.tabSearch.$el, tabSearchHeight)
            }
            if (this.$refs.compSearchs) {
                compSearchsHeight = this.$refs.compSearchs.$el.offsetHeight;
                // console.log('compSearchs', this.$refs.compSearchs.$el, compSearchsHeight)
            }
            if (this.$refs.compTool) {
                compToolHeight = this.$refs.compTool.offsetHeight;
                // console.log('compTool', this.$refs.compTool, compToolHeight)
            }
            if (this.$refs.compPage) {
                compPageHeight = this.$refs.compPage.$el.offsetHeight;
                // console.log('compPage', this.$refs.compPage.$el, compPageHeight)
            }
            if (this.$refs.comTemplate) {
                comTemplateHeight = this.$refs.comTemplate.$el.offsetHeight;
                // console.log('comTemplate', this.$refs.comTemplate.$el, comTemplateHeight)
            }
            let usedHeight =
                windowHeight -
                treeSearchHeight -
                tabSearchHeight -
                compSearchsHeight -
                compToolHeight -
                compPageHeight -
                comTemplateHeight -
                // 顶部navbar
                50 -
                // 顶部title
                45 -
                // 中间的3个margin，title tab search
                30 -
                // 最下方分页器的marginBottom

                // 分页器的marginTop
                15 -
                7;
            // let rowList = this.$refs.table.$el.querySelectorAll(
            //     ".ivu-table-row"
            // );
            let rowList = this.$refs.table.$el.querySelector('.ivu-table-body').querySelectorAll('tr');
            if (!rowList || !rowList.length) return usedHeight;
            // table数据列的总高度 解决每个row高度不同的问题
            let rowListHeight = 0;
            let rowArray = Array.from(rowList);
            rowArray.map(item => {
                rowListHeight += item.offsetHeight;
            })
            let rowHeight = rowList[0].offsetHeight;
            // let tableHeaderHeight = this.$refs.table.$el.querySelector('.ivu-table-header').querySelector('table').offsetHeight;
            let tableHeaderHeight = this.$refs.table.$el.querySelector('.ivu-table-header').querySelector('table').offsetHeight;
            // let rowListHeight = rowHeight * rowList.length + tableHeaderHeight;
            let tableHeight = rowListHeight + tableHeaderHeight;
            let resultHeight = 0;
            if (tableHeight < usedHeight) {
                // console.log('rowListHeight', rowListHeight)
                resultHeight = tableHeight;
            } else {
                // console.log('usedHeight', usedHeight)
                resultHeight = usedHeight;
            }
            if (resultHeight < rowHeight + tableHeaderHeight) return rowHeight + tableHeaderHeight;
            return resultHeight;
        },
        closeCloseable() {
            this.propsclosable = false;
        },
        openCloseable() {
            this.propsclosable = true;
        },
        //兼容老代码name属性
        // handleCompatibleLabel(data) {
        // 	return data.langKey ? $t(data.langKey, { defaultValue: data.name || data.label }) : (data.name || data.label)
        // },
        //兼容老代码val
        // handleValAndValue(item) {
        // 	return item.value === undefined ? item.val : item.value
        // },
        getCompsData(type) {
            return (
                this.getContextAttrs[type + "Data"] ||
                this.getContextAttrs[type]["data"]
            );
        },
        // handleActiveTab(item) {
        // 	const key = item.key || this.getContextAttrs.Tabs.key,
        // 		activeVal = this.formData.search[key],
        // 		val = this.handleValAndValue(item);
        // 	return activeVal === val ? 'primary' : 'default';
        // },
        updateSearch(data = {}, page = 1, stayModal = false) {
            if (data === null) {
                //修复tab和同字段搜索重置后无法切换
                this.formData.search = {};
            } else {
                this.formData.search = Object.assign(
                    this.formData.search || {},
                    data
                );
            }
            this.updateList({ page: page }, stayModal);
        },
        async updateRows (rows) {
            this.queryPage = true;
            this.formData.rows = rows;
            await this.updateList({ page: 1, rows: rows });
            this.queryPage = false;
        },
        async updatePage(page) {
            this.queryPage = true;
            await this.updateList({ page, rows: this.formData.rows });
            this.queryPage = false;
        },
        sortChange(sord, sidx) {
            this.updateList({ sidx, sord });
        },
        filterChange(value, key) {
            this.updateList({ [key]: value });
        },
        checkChange(rows) {
            // console.log(rows,val,'val')
            console.log(this.getTableAttrs, rows);
            let formName = this.getTableAttrs.columns.filter(item => {
                return item.type == 'selection';
            })[0];
            formName = formName.formName || "id";
            this.checkedData = rows.map(item => {
                return item[formName];
            });
            this.checkedRowData = rows;
        },
        getOperateNodes(h, { row }) {
            const operateNodes = [],
                operateTitle = this.$ct("global.common.operation");
            this.getOperateNodeMap(row).forEach((item = {}, index) => {
                if (item.show) {
                    if (item.to) {
                        operateNodes.push(
                            // <router-link
                            //     props={item}
                            // >
                            //     {item.label}
                            // </router-link>
                            h(resolveComponent('router-link'), {
                                ...item
                            }, item.label)
                        );
                    } else if (item.href) {
                        operateNodes.push(
                            <a props={item}>
                                {item.label}
                            </a>
                        );
                    } else {
                        operateNodes.push(
                            <div
                                key={index}
                                onClick={this.handleOperates.bind(
                                    this,
                                    item.params,
                                    item.operate,
                                    false
                                )}
                            >
                                {item.label}
                            </div>
                        );
                    }
                }
            });
            return (
                // <Dropdown
                //     placement="bottom-left"
                //     trigger="click"
                //     class="tablelist-dropdown"
                // >
                //     <Button size="small" theme="info">
                //         {operateTitle} <Icon type="md-arrow-dropdown" />
                //     </Button>
                //     <slot name="list" class="text-left">
                //         {operateNodes}
                //     </slot>
                // </Dropdown>
                h(resolveComponent("Dropdown"), {
                    placement: "bottom-start",
                    trigger: "click",
                    className: "tablelist-dropdown"
                }, {
                    default: () => h(resolveComponent("Button"), {
                        size: "small",
                        type: "info",
                    }, [
                        operateTitle,
                        h(resolveComponent("Icon"), {
                            type: "md-arrow-dropdown"
                        })
                    ]),
                    list: () => h(resolveComponent("DropdownMenu"), {
                        className: "tablelist-dropdown-menu text-left"
                    }, operateNodes)
                })
                // [
                //     h(resolveComponent("Button"), {
                //         size: "small",
                //         type: "info",
                //     }, [
                //         operateTitle,
                //         h(resolveComponent("Icon"), {
                //             type: "md-arrow-dropdown"
                //         })
                //     ]),
                //     h(resolveComponent("DropdownMenu"), )
                //     // h("template", {
                //     //     slot: "list"
                //     // }, operateNodes)
                // ])
            );
        },
        //用于清空主search数据
        cleanUpdateSearch(formData) {
            const search = this.formData.search;
            Object.keys(formData).forEach((key) => {
                // this.$set(search, key, formData[key]);
                search[key] = formData[key];
            });
            // this.$set(this.formData, "search", search);
            this.formData.search = search;
            this.$nextTick(() => {
                if (this.$refs.compSearchs) {
                    //切换 多页面tab 清空老历史的搜索条件
                    this.$refs.compSearchs.search();
                    return;
                }
                // this.updateSearch();
            });
        },
        // handleTabsSearch(item) {
        // 	const datalist = this.getCompsData("Tabs"),
        // 		tabskey = this.getContextAttrs.Tabs.key,
        // 		search = this.formData.search;
        // 	//用于处理附带数据
        // 	let attachData;
        // 	datalist.forEach(itemData => {
        // 		const key = itemData.key || tabskey;
        // 		const attach = itemData.attach;
        // 		if (attach && typeof attach === 'object') {
        // 			if (item === itemData) attachData = attach;
        // 			Object.keys(attach).forEach((key) => {
        // 				this.$set(search, key, "");
        // 			})
        // 		}
        // 		this.$set(search, key, "");
        // 	});
        // 	this.$set(search, item.key || tabskey, this.handleValAndValue(item));
        // 	if (attachData) {
        // 		Object.keys(attachData).forEach((key) => {
        // 			this.$set(search, key, attachData[key]);
        // 		})
        // 	}
        // 	this.$set(this.formData, "search", search);
        // 	this.$nextTick(() => {
        // 		if (this.$refs.compSearchs) {//切换 多页面tab 清空老历史的搜索条件
        // 			this.$refs.compSearchs.search();
        // 			return;
        // 		}
        // 		this.updateSearch();
        // 	})
        // },
        handleOperates(data, type) {},
        //用于处理自定义参数结构
        // _interceptRequest() {

        // },
        async updateList(data = {}, stayModal = false) {
            if (!stayModal) {
                // this.operate = {};
                this.handleModalClose();
            }
            // this.operate = {};
            this.handleModalClose();
            this.loading = true;
            this.formData = Object.assign(this.formData, data);
            const {
                interceptRequest,
                interceptResponse,
                ajaxRequest,
                spanAjaxRequest,
            } = this.getContextAttrs;
            if (this.getContextAttrs.spanTabs) {
                spanAjaxRequest()
                    .then((res) => {
                        this.spansData = res.data;
                        this.computedTableHeight().then((height) => {
                            this.computedHeight = height;
                        });
                    })
                    .catch((err) => {
                        this.loading = false;
                        this.$Message.error({
                            content: err.message,
                            duration: 30,
                            closable: true
                        });
                    });
            }
            if (typeof ajaxRequest === "function") {
                let params = { ...this.formData };
                if (typeof interceptRequest === "function")
                    params = interceptRequest.call(
                        this,
                        JSON.parse(JSON.stringify(params)),
                        this
                    );
                return ajaxRequest(params)
                    .then((res) => {
                        const data = res.data || {};
                        this.loading = false;
                        this.total = data.totalElements || 0;
                        this.dataList = data.content || [];
                        if (typeof interceptResponse === "function") {
                            interceptResponse.call(this, data, this);
                        } else if (
                            this.dataList[0] !== undefined &&
                            typeof this.dataList[0] !== "object"
                        ) {
                            //针对[1,2,3]组件报错问题
                            this.dataList = this.dataList.map((val) => {
                                return {
                                    key: val,
                                };
                            });
                        }
                        this.computedTableHeight().then((height) => {
                            this.computedHeight = height;
                        });
                    })
                    .catch((err) => {
                        this.loading = false;
                        this.$Message.error({
                            content: err.message,
                            duration: 30,
                            closable: true
                        });
                    });
            }
        },
    },
};
</script>
